package com.lagou.edu.factory;

import com.lagou.edu.pojo.Account;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author chenx
 *
 *
 * 代理对象工厂：生成代理对象的
 */

public class ProxyFactory {


    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * jdk动态代理
     * 需要定义有接口
     * @param target
     * @return
     */
    public  Object getJdkProxy(Object target){
        return Proxy.newProxyInstance(this.getClass().getClassLoader()
                , target.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        try{
                            //开始事物
                            transactionManager.beginTransaction();
                            //执行方法
                            result = method.invoke(target,args);
                            //提交事物
                            transactionManager.commit();

                        }catch (Exception e){
                            //事物回滚
                            transactionManager.rollback();
                            //向上抛出，便于servlet中捕获
                            throw e.getCause();
                        }
                        return result;
                    }
                });
    }

    /**
     * cglib动态代理
     * @param obj
     * @return
     */
    public Object getCglibProxy(Object obj){
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try{
                    //开始事物
                    transactionManager.beginTransaction();
                    //执行方法
                    result = method.invoke(obj,objects);
                    //提交事物
                    transactionManager.commit();
                }catch (Exception e){

                }
                return result;
            }
        });


    }
}
